package cn.yllr.tomgxianghui.listener;

import cn.yllr.tomgxianghui.dao.OrderMapper;
import cn.yllr.tomgxianghui.domain.Order;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    @Autowired
    private OrderMapper mapper;


    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 监听redis的过期时间，写业务逻辑
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {

        String orderCode = message.toString();

        if (!StringUtils.isBlank(orderCode)) {

            // 去数据库把订单状态改成过期,这里是我们的业务逻辑
            Order order = new Order();
            order.setOrderStatus(0); // 5表示订单状态是过期
            order.setOrderid(orderCode);
            mapper.updateOrderStstus(order);
        }

        System.out.println("过期的订单号是: " + orderCode);

    }


}
